<template>
  <div>
    <div v-for="(item, index) in dataList" :key="index" class="item" @click="handleClick(item)">
      <div class="label-row">
        <span class="label">{{ item.name }}</span>
        <span class="count">{{ item.count }}人</span>
      </div>
      <div class="value-row" :style="getBarStyle(index)">
        <div class="content" :style="{ ...getContentStyle(item, index) }"></div>
        <div class="dot-wrap" :style="getDotWrapStyle(index)">
          <div class="dot" :style="getDotStyle(index)"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "g-horizontal-bar",
  props: {
    dataList: {
      type: Array,
      default: () => [],
    },
    colorList: {
      type: Array,
      default: () => ["#39eba5", "#8bfdf9", "#ede67b", "#ff4d4f", "#a8a4ff"],
    },
  },
  computed: {
    totalCount() {
      return this.dataList.reduce((acc, item) => acc + item.count, 0);
    },
  },
  methods: {
    handleClick(item) {
      this.$emit("clickBar", item);
    },
    getBarStyle(index) {
      const color = this.colorList[index % this.colorList.length];
      return {
        background: "rgba(0, 75, 177, 0.18)",
      };
    },
    getDotWrapStyle(index) {
      const color = this.colorList[index % this.colorList.length];
      return {
        outline: `1px solid ${this.hexToRgba(color, 0.7)}`,
        border: `5px solid ${this.hexToRgba(color, 0.2)}`,
      };
    },
    getDotStyle(index) {
      const color = this.colorList[index % this.colorList.length];
      return {
        background: color,
      };
    },
    getContentStyle(item, index) {
      const color = this.colorList[index % this.colorList.length];
      const percentage = (item.count / this.totalCount) * 100;
      return {
        width: percentage + "%",
        background: `linear-gradient(90deg, rgba(0, 75, 177, 0.18) 0%, ${color} 100%)`,
      };
    },
    hexToRgba(hex, alpha) {
      const r = parseInt(hex.slice(1, 3), 16);
      const g = parseInt(hex.slice(3, 5), 16);
      const b = parseInt(hex.slice(5, 7), 16);
      return `rgba(${r}, ${g}, ${b}, ${alpha})`;
    },
  },
};
</script>
<style scoped lang="scss">
.item {
  width: 100%;
  margin-bottom: 24px;
  padding: 0 6px;
  box-sizing: border-box;
  .label-row {
    width: 100%;
    font-size: 16px;
    color: #ffffff;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    span {
      font-family: STHeitiTC;
    }
    .count {
      color: #00f3ff;
    }
  }
  .value-row {
    width: 100%;
    height: 7px;
    border-radius: 2px;
    display: flex;
    align-items: center;
    .content {
      height: 7px;
      border-radius: 2px;
      transition: width 0.3s ease-in;
    }
    .dot-wrap {
      margin-left: -4px;
      border-radius: 50%;
      .dot {
        width: 6px;
        height: 6px;
        border-radius: 50%;
      }
    }
  }
}
</style>
